package cn.ssm.ssm_admin;
// 中介者接口
interface Mediator {
    void sendMessage(String message, Colleague colleague); // 定义发送消息的方法
}

// 具体中介者
class ConcreteMediator implements Mediator {
    private Colleague colleague1; // 具体中介者维护对具体同事对象1的引用
    private Colleague colleague2; // 具体中介者维护对具体同事对象2的引用

    public void setColleague1(Colleague colleague1) {
        this.colleague1 = colleague1;
    }

    public void setColleague2(Colleague colleague2) {
        this.colleague2 = colleague2;
    }

    @Override
    public void sendMessage(String message, Colleague colleague) {
        if (colleague == colleague1) {
            colleague2.receiveMessage(message); // 如果发送者是同事对象1，则将消息转发给同事对象2
        } else if (colleague == colleague2) {
            colleague1.receiveMessage(message); // 如果发送者是同事对象2，则将消息转发给同事对象1
        }
    }
}

// 抽象同事类
abstract class Colleague {
    protected Mediator mediator; // 抽象同事类中包含对中介者的引用

    public Colleague(Mediator mediator) {
        this.mediator = mediator;
    }

    public abstract void sendMessage(String message); // 定义发送消息的方法
    public abstract void receiveMessage(String message); // 定义接收消息的方法
}

// 具体同事类1
class ConcreteColleague1 extends Colleague {
    public ConcreteColleague1(Mediator mediator) {
        super(mediator);
    }

    @Override
    public void sendMessage(String message) {
        mediator.sendMessage(message, this); // 通过中介者发送消息
    }

    @Override
    public void receiveMessage(String message) {
        System.out.println("ConcreteColleague1 received: " + message); // 接收消息并打印
    }
}

// 具体同事类2
class ConcreteColleague2 extends Colleague {
    public ConcreteColleague2(Mediator mediator) {
        super(mediator);
    }

    @Override
    public void sendMessage(String message) {
        mediator.sendMessage(message, this); // 通过中介者发送消息
    }

    @Override
    public void receiveMessage(String message) {
        System.out.println("ConcreteColleague2 received: " + message); // 接收消息并打印
    }
}

// 示例代码
public class MediatorPatternExample {
    public static void main(String[] args) {
        ConcreteMediator mediator = new ConcreteMediator(); // 创建具体中介者对象
        ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator); // 创建具体同事对象1
        ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator); // 创建具体同事对象2

        mediator.setColleague1(colleague1); // 将具体同事对象1注册到具体中介者中
        mediator.setColleague2(colleague2); // 将具体同事对象2注册到具体中介者中

        colleague1.sendMessage("Hello"); // 同事对象1发送消息
        colleague2.sendMessage("Hi"); // 同事对象2发送消息
    }
}